/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */

import React, {
  PropTypes
} from 'react';
import BaseComponent from "../BaseComponent";
import styles from './HomePage.css';
import withStyles from '../../decorators/withStyles';
import withViewport from '../../decorators/withViewport';
import StoryActionCreators from '../../actions/StoryActionCreators';
import StoryStore from '../../stores/StoryStore';

@withViewport
@withStyles(styles)
class HomePage extends BaseComponent {

  static propTypes = {
    viewport: PropTypes.shape({
      width: PropTypes.number.isRequired,
      height: PropTypes.number.isRequired
    })
      .isRequired
  };

  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired
  };

  constructor(props, context) {
    super(props);
    this.state = this.getState();
    this.stores = [StoryStore];
    StoryActionCreators.loadStories();
  }

  getState() {
    return {
      stories: StoryStore.getAll(),
      nextPage: StoryStore.nextPage(),
      loading: StoryStore.loading()
    };
  }

  loadMoreStories() {
    StoryActionCreators.loadStories(this.state.nextPage);
  }

  render() {
    const title = '首页';
    this.context
      .onSetTitle(title);

    const {width, height} = this.props.viewport;

    let getCardStyle = {
      width: (width - 4) / 3,
      height: (width - 4) / 2.4
    };

    let nodes = this
      .state
      .stories
      .map(function(story, index) {
        return (
          <div className="thumbnail" key={'card-' + index} style={getCardStyle}>
            <div className="layer">
              <div className="full-relative">
                <div className="Card__bg" style={{
                  backgroundImage: 'url(' + story.card_url + '@200w_250h_1e_1c)'
                }}></div>
              </div>
            </div>
          </div>
        );
      });

    let loading = <div className="Post__moreLoadingIndicator" disabled>
        <a className="Post__moreLink">加载中</a>
      </div>;
    let loaded = <div className="Post__moreLoadingIndicator" onClick={this
        .loadMoreStories
        .bind(this)}>
        <a className="Post__moreLink">加载更多</a>
      </div>;

    return (
      <div className="HomePage">
        <div className="HomePage-container">
          <div className="Photo__cards">
            {nodes}
          </div>
          {this.state.loading
            ? loading
            : loaded}
        </div>
      </div>
    );
  }

}

export default HomePage;
